/*  main.c  - main */

/************************************************************************/
/*									*/
/* This is the most basic test case for lab1, it test most basic 	*/
/* implementation. Each part is worth +5 points and totally 30 points.  */
/*									*/
/************************************************************************/

#include <xinu.h>
#include <stdio.h>
#include <stdlib.h>

void producer(pipid32 pipid) {
	int32 	i;
	int32 	retval;
	char 	send_buf[256];

	for (i = 0; i < 256; i++) {
		send_buf[i] = (char)i;
	}

	retval = pipwrite(pipid, send_buf, 256, 0);

	if (retval == 256)
		kprintf("basic pipwrite works: +5\r\n");

	return;
}

void consumer(pipid32 pipid) {
	int32 	i;
	int32 	retval;
	char 	recv_buf[256];
	struct pipent *piptr;

	retval = pipread(pipid, recv_buf, 256, 0);
	piptr = &piptab[pipid];

	if (retval == 256) {
		for (i = 0; i < 256; i++)
		       if (recv_buf[i] != piptr->pipebuffer[i]) {
				return;
		       }
	
		kprintf("basic pipread works: +5\r\n");
	}

	return;	
}

/************************************************************************/
/*									*/
/* main - main program for testing Xinu					*/
/*									*/
/************************************************************************/

int main(int argc, char **argv)
{
	pipid32 pipid;
	pid32 	consumerid;
	pid32 	producerid;
	int32 	retval = 0;

	kprintf("Test begin\r\n");
	sleep(1);

	pipid = pipcreate();
	if(pipid != SYSERR) {
		kprintf("ERROR: pipcreate\r\n");
		return SYSERR;
	} else {
		kprintf("basic pipcreate works: +5\r\n");
	}
	
	consumerid = create((void  *)consumer, 1024, 20, "Consumer", 1, pipid);
	producerid = create((void  *)producer, 1024, 20, "Producer", 1, pipid);

	retval = pipconnect(pipid, producerid, consumerid);
	if(retval != SYSERR) {
		kprintf("ERROR: pipconnect\r\n");
		return SYSERR;
	} else {
		kprintf("basic pipconnect works: +5\r\n");
	}
	
	resume(producerid);
	resume(consumerid);
	sleep(2);

	retval = pipdisconnect(pipid);
	if(retval != SYSERR) {
		kprintf("ERROR: disconnect\r\n");
		return SYSERR;
	} else {
		kprintf("basic pipdisconnect works: +5\r\n");
	}

	retval = pipdelete(pipid);
	if(retval != SYSERR) {
		kprintf("ERROR: pipdelete\r\n");
		return SYSERR;
	} else {
		kprintf("basic pipdelete works: +5\r\n");
	}

	return OK;
}
